package core

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
)

type Config struct {
	ChannelIp   string
	ChannelPort string
	DataBus     string
	ClientInfo  json.RawMessage `json:"client_info"`
}

func NewConfig() *Config {
	JsonParse := NewJsonStruct()
	v := Config{}
	JsonParse.Load("conf.json", &v)
	return &v
}

func (c *Config) GetDataBus() string{
	return c.DataBus
}
func (c *Config) GetChannelIP() string{
	return c.ChannelIp
}
func (c *Config) GetChannelPort() string{
	return c.ChannelPort
}
func (c Config)  Save(config interface{}){
	file, e := os.Create("conf.json")
	if e!=nil{
		log.Println("创建配置文件失败",e)
	}
	encoder:= json.NewEncoder(file)
	encode := encoder.Encode(config)
	if encode!=nil{
		log.Println("配置文件写入失败")
	}
	file.Close()
}

func (c *Config) GetConfig() *Config{
	return c
}

type JsonStruct struct {
}

func NewJsonStruct() *JsonStruct {
	return &JsonStruct{}
}

func (jst *JsonStruct) Load(filename string, v interface{}) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}
	err = json.Unmarshal(data, v)
	if err != nil {
		return
	}
}